package com.eeb.dropwizardmongo.example;

import com.eeb.dropwizardmongo.configuration.DropwizardMongoConfiguration;
import com.eeb.dropwizardmongo.example.api.*;
import com.eeb.dropwizardmongo.example.resources.*;
import com.eeb.dropwizardmongo.health.MongoHealthCheck;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.mongojack.JacksonDBCollection;

/**
 * Dropwizard application with DropwizardMongoConfiguration type.
 */
public class DropwizardMongoApplication extends Application<DropwizardMongoConfiguration> {

    public static void main (String[] args) throws Exception {
        new DropwizardMongoApplication().run(new String[]{"server", "config.yaml"});
    }

    @Override
    public void initialize(Bootstrap<DropwizardMongoConfiguration> bootstrap) {
    }

    @Override
    public void run(DropwizardMongoConfiguration config, Environment environment) throws Exception {
        final MongoClient mongoClient = config.getMongoFactory().buildClient(environment);
        final DB db = config.getMongoFactory().buildDB(environment);

        MongoManaged mongoManaged = new MongoManaged(mongoClient);
        environment.lifecycle().manage(mongoManaged);

        environment.healthChecks().register("mongo", new MongoHealthCheck(mongoClient));

        JacksonDBCollection<History, String> history = JacksonDBCollection.wrap(
                db.getCollection("users"), History.class, String.class);
        environment.jersey().register(new HistoryResource(history));

        JacksonDBCollection<User, String> users = JacksonDBCollection.wrap(
                db.getCollection("users"), User.class, String.class);
        environment.jersey().register(new UsersResource(users));

        JacksonDBCollection<Organization, String> organizations = JacksonDBCollection.wrap(
                db.getCollection("organizations"), Organization.class, String.class);
        environment.jersey().register(new OrganizationsResource(organizations));

        JacksonDBCollection<Track, String> tracks = JacksonDBCollection.wrap(
                db.getCollection("tracks"), Track.class, String.class);
        environment.jersey().register(new TracksResource(tracks));

        JacksonDBCollection<Assignment, String> assignments = JacksonDBCollection.wrap(
                db.getCollection("assignments"), Assignment.class, String.class);
        environment.jersey().register(new AssignmentsResource(assignments));

        JacksonDBCollection<Badge, String> badges = JacksonDBCollection.wrap(
                db.getCollection("badges"), Badge.class, String.class);
        environment.jersey().register(new BadgesResource(badges));
    }

}
